package com.water.bs.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.water.bs.pojo.EmailCode;
import com.water.bs.pojo.Organization;
import com.water.bs.service.EmailService;
import com.water.bs.service.OrgService;
import com.water.bs.service.UserDonationService;
import com.water.bs.utils.MailUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.*;

@CrossOrigin
@RestController
public class OrgController {
    @Autowired
    private OrgService orgService;
    @Autowired
    private EmailService emailService;
    @Autowired
    private UserDonationService userDonationService;
    @Autowired
    private MailUtil mailUtil;

    @RequestMapping("/getOrgHead")
    public void getOrgHead(@RequestParam("id")String id, final HttpServletResponse response) throws IOException {
        Organization org = orgService.getOrgHead(id);
        byte[] data = org.getHead();
        response.setContentType("image/jpeg");
        response.setCharacterEncoding("UTF-8");
        OutputStream outputStream = response.getOutputStream();
        InputStream in = new ByteArrayInputStream(data);
        int len = 0;
        byte[] buf = new byte[1024];
        while ((len = in.read(buf, 0, 1024)) != -1) {
            outputStream.write(buf, 0, len);
        }
        outputStream.close();
    }

    @RequestMapping("/saveOrgHead")
    public JSON saveUserHead(@RequestParam("file") MultipartFile file, @RequestParam("id") String id){
        JSONObject rs = new JSONObject();
        System.out.println(file);
        System.out.println(id);
        Map<String,Object> map = new HashMap<>();
        if (file.isEmpty()){
            rs.put("state","1");
            rs.put("message","上传失败,请重新选择!");
            return rs;
        }
        try {
            InputStream is = file.getInputStream();
            byte[] photoFile = new byte[(int)file.getSize()];
            System.out.println(file.getSize());
            is.read(photoFile);
            map.put("photofile",photoFile);
            map.put("id",id);
            int i = orgService.saveOrgHead(map);
            if (i>0){
                rs.put("state","0");
                rs.put("message","保存成功");
            }else{
                rs.put("state","1");
                rs.put("message","上传失败!");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return rs;

    }
    @RequestMapping("/editOrg")
    public JSON editOrg(@RequestBody JSONObject editOrgInfo){
        JSONObject rs = new JSONObject();
        Map<String,Object> map = new HashMap<>();
        System.out.println("修改的机构信息是"+editOrgInfo);
        String editEmail = (String) editOrgInfo.get("email");
        if (editEmail !=null ||editEmail!="") {
            int emailRepeat = orgService.isEmailRepeat(editEmail);
            if (emailRepeat>0){
                rs.put("state","3");
                rs.put("message","邮箱号已被注册!");
                return rs;
            }
        }
        map.put("id",editOrgInfo.get("id"));
        if (editOrgInfo.get("password")!=null){
            String s = (String) editOrgInfo.get("password");
            map.put("password", DigestUtils.md5DigestAsHex(s.getBytes())); //md5
        }
        if (editOrgInfo.get("email")!=null){
            String lowerCaseEmail = ((String) editOrgInfo.get("email")).toLowerCase();  //把注册时的邮箱 变成小写再存到数据库
            map.put("email",lowerCaseEmail);
        }
        if (editOrgInfo.get("phone")!=null){
            map.put("phone",editOrgInfo.get("phone"));
        }
        if (editOrgInfo.get("city")!=null){
            map.put("city",editOrgInfo);
        }
        if (editOrgInfo.get("address")!=null){
            map.put("address",editOrgInfo.get("address"));
        }
        if (editOrgInfo.get("orgname")!=null){
            map.put("orgname",editOrgInfo.get("orgname"));
        }
        if (editOrgInfo.get("orgmsg")!=null){
            map.put("orgmsg",editOrgInfo.get("orgmsg"));
        }
        System.out.println(map);
        int i = orgService.updateOrg(map);
        if (i ==1){
            rs.put("state","0");
            rs.put("message","修改完成!");
            return rs;
        }else{
            rs.put("state","1");
            rs.put("message","操作失败!");
            return rs;
        }

    }




    @RequestMapping("/qryForMeDonation")   //审批捐赠给我的
    public JSON qryForMeDonation(@RequestParam("orgid")String orgid){
        JSONObject rs = new JSONObject();
        System.out.println("机构id:"+orgid);
        List<Map<String, Object>> maps = orgService.qryForMeDonation(orgid);
        for (Map<String, Object> map : maps) {
            List<Map<String, Object>> dodetail = userDonationService.qryMyDonationDetail((String) map.get("doid"));
            map.put("dodetail",dodetail);
        }
        rs.put("data",maps);
        return rs;
    }

    @RequestMapping("/agreeDo")
    public JSON agreeDo(@RequestBody JSONObject agreeDoInfo){
        JSONObject rs = new JSONObject();
        System.out.println("通过审批捐赠信息:"+agreeDoInfo);
//        {"createtime":"1648042752399","dostate":"1","nickname":"炸裂狂神233","doid":"a6a704f4-28ca-4b25-8a8c-4372b989f09a","doexpress":"1111233323","userid":"1bd16ae4-24cb-43a8-8ada-b6cd63aeeaa0","point":180,"orgid":"18b2db22-77c5-4cb4-8f23-3aaf6f56d905","dodetail"
        int i = orgService.agreeDo(agreeDoInfo);
        if (i >0){
            rs.put("state","0");
            rs.put("message","操作完成!");
            return rs;
        }else{
            rs.put("state","1");
            rs.put("message","操作失败!");
            return rs;
        }
    }

    @RequestMapping("/doFoMeHiotory")  //查询用户捐赠给我的历史列表
    public JSON doFoMeHiotory(@RequestParam("orgid")String orgid){
        JSONObject rs = new JSONObject();
        System.out.println("机构id:"+orgid);
        List<Map<String, Object>> maps = orgService.doFoMeHiotory(orgid);
        for (Map<String, Object> map : maps) {
            List<Map<String, Object>> dodetail = userDonationService.qryMyDonationDetail((String) map.get("doid"));
            map.put("dodetail",dodetail);
        }
        rs.put("data",maps);
        return rs;
    }
    @RequestMapping("/createOrgNotice")  //创建动态
    public JSON createOrgNotice(HttpServletRequest request) throws IOException {
        JSONObject rs = new JSONObject();
        MultipartHttpServletRequest params=((MultipartHttpServletRequest) request);
        MultipartFile file = ((MultipartHttpServletRequest) request).getFile("file");
        System.out.println("接收到的图片:"+file);
        Map<String,Object> map = new HashMap<>();
        map.put("orgid",params.getParameter("orgid"));
        map.put("title",params.getParameter("title"));
        map.put("msg",params.getParameter("msg"));
        map.put("id",UUID.randomUUID().toString());
        map.put("createtime",System.currentTimeMillis());
        System.out.println("接收到的信息:"+map);
        //{id=c8124c17-bf7d-438c-87ae-d925f3efa665, title=123, orgid=18b2db22-77c5-4cb4-8f23-3aaf6f56d905,msg=23132}
        int i =0;
        try {
            InputStream is = file.getInputStream();
            byte[] photoFile = new byte[(int)file.getSize()];
            System.out.println(file.getSize());
            is.read(photoFile);
            map.put("photofile",photoFile);
            i = orgService.createOrgNotice(map);

        } catch (IOException e) {
            e.printStackTrace();
        }

        if (i >0){
            rs.put("state","0");
            rs.put("message","操作完成!");
            return rs;
        }else{
            rs.put("state","1");
            rs.put("message","操作失败!");
            return rs;
        }
    }

    @RequestMapping("/qryOrgNoticeList")  //查询动态列表
    public JSON qryOrgNoticeList(@RequestParam("orgid")String orgid){
        JSONObject rs = new JSONObject();
        System.out.println("要查询的机构id是"+orgid);
        List<Map<String, Object>> maps = orgService.qryOrgNoticeList(orgid);
        rs.put("data",maps);
        return rs;
    }

    @RequestMapping("/getNoticePhoto")
    public void getNoticePhoto(@RequestParam("id")String id, final HttpServletResponse response) throws IOException {
        Map<String,Object> org = orgService.getNoticePhoto(id);
        byte[] data = (byte[]) org.get("img");
        response.setContentType("image/jpeg");
        response.setCharacterEncoding("UTF-8");
        OutputStream outputStream = response.getOutputStream();
        InputStream in = new ByteArrayInputStream(data);
        int len = 0;
        byte[] buf = new byte[1024];
        while ((len = in.read(buf, 0, 1024)) != -1) {
            outputStream.write(buf, 0, len);
        }
        outputStream.close();
    }

    @RequestMapping("/forgetPwdOrg")
    public JSON forgetPwdOrg(@RequestBody JSONObject forgetInfo){
        JSONObject rs = new JSONObject();
        String lowEmail = (String)forgetInfo.get("email");
        int i = orgService.isEmailRepeat(lowEmail);
        if (i<1){
            rs.put("state","1");
            rs.put("message","此邮箱尚未注册!");
            return rs;
        }
        forgetInfo.put("email",lowEmail.toLowerCase());
        String s = (String) forgetInfo.get("pwd");
        forgetInfo.put("pwd",DigestUtils.md5DigestAsHex(s.getBytes()));
        System.out.println("忘记密码请求"+forgetInfo);
        //忘记密码请求{"code":"1234","pwd":"bbf2dead374654cbb32a917afd236656","email":"694886886@qq.com"}
        EmailCode emailcode = emailService.getEmailCode((String) forgetInfo.get("email"));
        if (emailcode==null ){
            rs.put("state","2");
            rs.put("message","请获取邮箱验证码进行验证!");
            return rs;
        }
        if (emailcode.getCode().equals(forgetInfo.get("code")) && mailUtil.emailCodeAble(emailcode.getSendTime())) { //验证码验证成功(验证码正确并且再有效期)
            int i1 = orgService.forgetPwd(forgetInfo);
            if (i1>0){
                rs.put("state","0");
                rs.put("message","操作成功!");
                return rs;
            }else{
                rs.put("state","3");
                rs.put("message","操作失败!");
                return rs;
            }
        }else{
            rs.put("state","4");
            rs.put("message","验证码错误或已失效!");
            return rs;
        }
    }

}
